#pragma once
#include <iostream>
#include <unordered_map>
#include <stdio.h>
#include <cstring>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <functional>
#include <pthread.h>
using namespace std;

class User
{
public:
    User(const string &ip, const uint16_t &port)
        : _ip(ip), _port(port)
    {
    }
    ~User() {}
    string getip()
    {
        return _ip;
    }
    uint16_t getport()
    {
        return _port;
    }
private:
    string _ip;
    uint16_t _port;
};

class Users
{
public:
    Users()
    {
    }
    ~Users()
    {
    }
    void addUser(const string &ip, const uint16_t &port)
    {
        string s = ip + "-" + to_string(port);
        onlineUsers.insert(make_pair(s,User(ip,port)));
    }
    void delUser(const string &ip, const uint16_t &port)
    {
        string s = ip + "-" +to_string(port);
        onlineUsers.erase(s);
    }
    bool isOnline(const string &ip,const uint16_t& port)
    {
        string s = ip + "-" + to_string(port);
        return onlineUsers.find(s) == onlineUsers.end() ? false : true;
    }
    void broadcastMessage(int sockfd, const string &ip, const uint16_t &port, const string &messages)
    {
        for (auto &usr : onlineUsers)
        {
            struct sockaddr_in respose;
            bzero(&respose, sizeof(respose));

            respose.sin_family = AF_INET;
            respose.sin_port = htons(usr.second.getport());
            respose.sin_addr.s_addr = inet_addr(usr.second.getip().c_str());
            //拼接信息
            string sendmessage = ip +"-"+ to_string(port)+"#";
            sendmessage+=messages;
            sendto(sockfd, sendmessage.c_str(), sendmessage.size(), 0, (struct sockaddr *)&respose, sizeof(respose));
        }
    }

private:
    unordered_map<string, User> onlineUsers;
};
